using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Microsoft.Web.WebView2.Core;
using Microsoft.Web.WebView2.WinForms;
using Newtonsoft.Json;

namespace BW.Mes.WinForms.Common
{
    /// <summary>
    /// 可嵌入Vue3应用的WebView控件
    /// </summary>
    public partial class VueWebView : UserControl
    {
        private WebView2 webView;
        private string _baseUrl = "http://localhost:5173"; // 默认Vue开发服务器地址
        private bool _isInitialized = false;
        private Dictionary<string, Func<string, Task<string>>> _registeredJsCallbacks = new Dictionary<string, Func<string, Task<string>>>();

        /// <summary>
        /// Vue应用的基础URL
        /// </summary>
        [Category("WebView"), Description("Vue应用的基础URL")]
        public string BaseUrl
        {
            get { return _baseUrl; }
            set
            {
                _baseUrl = value;
                if (_isInitialized && webView != null)
                {
                    NavigateToUrl(_baseUrl);
                }
            }
        }

        /// <summary>
        /// Vue应用的路径，相对于BaseUrl
        /// </summary>
        [Category("WebView"), Description("Vue应用的路径，相对于BaseUrl")]
        public string Path { get; set; } = "/";

        /// <summary>
        /// WebView初始化完成事件
        /// </summary>
        public event EventHandler WebViewInitialized;

        public VueWebView()
        {
            InitializeWebView();
        }

        private void InitializeComponent()
        {
            this.SuspendLayout();
            // 
            // VueWebView
            // 
            this.Name = "VueWebView";
            this.Size = new System.Drawing.Size(800, 600);
            this.ResumeLayout(false);
        }

        private async void InitializeWebView()
        {
            try
            {
                InitializeComponent();

                // 创建WebView2控件
                webView = new WebView2();
                webView.Dock = DockStyle.Fill;
                webView.CreationProperties = new CoreWebView2CreationProperties
                {
                    UserDataFolder = $"{Application.StartupPath}\\WebView2Data"
                };

                // 添加到控件中
                this.Controls.Add(webView);

                // 初始化WebView2环境
                await webView.EnsureCoreWebView2Async();

                // 配置WebView2设置
                webView.CoreWebView2.Settings.IsScriptEnabled = true;
                webView.CoreWebView2.Settings.AreDefaultScriptDialogsEnabled = true;
                webView.CoreWebView2.Settings.IsWebMessageEnabled = true;
                webView.CoreWebView2.Settings.AreDevToolsEnabled = true;

                // 添加WebMessage事件处理
                webView.CoreWebView2.WebMessageReceived += CoreWebView2_WebMessageReceived;

                // 标记为已初始化
                _isInitialized = true;

                // 导航到Vue应用
                NavigateToUrl(_baseUrl + Path);

                // 触发初始化完成事件
                WebViewInitialized?.Invoke(this, EventArgs.Empty);
            }
            catch (Exception ex)
            {
                MessageBox.Show($"WebView2初始化失败: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        /// <summary>
        /// 导航到指定URL
        /// </summary>
        public void NavigateToUrl(string url)
        {
            if (webView != null && _isInitialized)
            {
                webView.CoreWebView2.Navigate(url);
            }
        }

        /// <summary>
        /// 导航到Vue应用的指定路径
        /// </summary>
        public void NavigateToVuePath(string path)
        {
            if (webView != null && _isInitialized)
            {
                webView.CoreWebView2.Navigate(_baseUrl + path);
            }
        }

        /// <summary>
        /// 注册一个可从JavaScript调用的C#回调函数
        /// </summary>
        public void RegisterJsCallback(string functionName, Func<string, Task<string>> callback)
        {
            _registeredJsCallbacks[functionName] = callback;
        }

        /// <summary>
        /// 执行JavaScript代码
        /// </summary>
        public async Task<string> ExecuteScriptAsync(string script)
        {
            if (webView != null && _isInitialized)
            {
                return await webView.CoreWebView2.ExecuteScriptAsync(script);
            }
            return null;
        }

        /// <summary>
        /// 调用Vue应用中的JavaScript函数
        /// </summary>
        public async Task<string> CallVueMethodAsync(string methodName, params object[] args)
        {
            if (webView != null && _isInitialized)
            {
                string argsJson = JsonConvert.SerializeObject(args);
                string script = $"window.{methodName}({argsJson.Substring(1, argsJson.Length - 2)})";
                return await webView.CoreWebView2.ExecuteScriptAsync(script);
            }
            return null;
        }

        /// <summary>
        /// 向Vue应用发送数据
        /// </summary>
        public async Task SendDataToVueAsync(string eventName, object data)
        {
            if (webView != null && _isInitialized)
            {
                string dataJson = JsonConvert.SerializeObject(data);
                string script = $"window.dispatchEvent(new CustomEvent('{eventName}', {{ detail: {dataJson} }}))";
                await webView.CoreWebView2.ExecuteScriptAsync(script);
            }
        }

        /// <summary>
        /// 处理从Vue应用接收的WebMessage
        /// </summary>
        private async void CoreWebView2_WebMessageReceived(object sender, CoreWebView2WebMessageReceivedEventArgs e)
        {
            try
            {
                // 解析收到的消息
                var message = JsonConvert.DeserializeObject<dynamic>(e.WebMessageAsJson);
                string type = message.type;
                string functionName = message.function;
                string data = message.data?.ToString();
                string callbackId = message.callbackId?.ToString();

                if (type == "functionCall" && !string.IsNullOrEmpty(functionName))
                {
                    // 查找并调用注册的回调函数
                    if (_registeredJsCallbacks.TryGetValue(functionName, out var callback))
                    {
                        try
                        {
                            string result = await callback(data);
                            
                            // 发送结果回Vue应用
                            if (!string.IsNullOrEmpty(callbackId))
                            {
                                await webView.CoreWebView2.ExecuteScriptAsync(
                                    $"window.__receiveNativeCallback('{callbackId}', {JsonConvert.SerializeObject(result)}, null)");
                            }
                        }
                        catch (Exception ex)
                        {
                            // 发送错误回Vue应用
                            if (!string.IsNullOrEmpty(callbackId))
                            {
                                await webView.CoreWebView2.ExecuteScriptAsync(
                                    $"window.__receiveNativeCallback('{callbackId}', null, {JsonConvert.SerializeObject(ex.Message)})");
                            }
                        }
                    }
                    else
                    {
                        // 函数未注册，发送错误回Vue应用
                        if (!string.IsNullOrEmpty(callbackId))
                        {
                            await webView.CoreWebView2.ExecuteScriptAsync(
                                $"window.__receiveNativeCallback('{callbackId}', null, 'Function not registered: {functionName}')");
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"处理WebMessage失败: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        /// <summary>
        /// 释放资源
        /// </summary>
        protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                if (webView != null)
                {
                    if (_isInitialized)
                    {
                        webView.CoreWebView2.WebMessageReceived -= CoreWebView2_WebMessageReceived;
                    }
                    webView.Dispose();
                    webView = null;
                }
            }
            base.Dispose(disposing);
        }
    }
} 